package com.syg.boot.core.builder;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yaml.snakeyaml.Yaml;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author syg
 * @version 1.0
 * @date 2021年11月24日16:32:43
 */
public class YamlReader {
    private static final Logger log = LoggerFactory.getLogger(YamlReader.class);

    private static Map<String, Map<String, Object>> properties = new HashMap<>();
    public static final YamlReader INSTANCE = new YamlReader();

    public YamlReader() {

    }

    public Object getValue(String fileName, String key) {
        Yaml yaml = new Yaml();
        InputStream in;
        try {
            in = YamlReader.class.getClassLoader().getResourceAsStream(fileName);
            properties = yaml.loadAs(in, HashMap.class);
        } catch (Throwable e) {
            log.error("Application start YamlReader error,", e);
            throw e;
        } finally {
            // in 需要关闭
        }

        String separator = ".";
        if (!key.contains(separator)) {
            return properties.get(key);
        }

        String[] separatorKeys = key.split(separator);
        Object finalValue = new HashMap<>(16);
        for (int i = 0; i < separatorKeys.length - 1; ++i) {
            if (i == 0) {
                finalValue = properties.get(separatorKeys[i]);
            } else {
                if (finalValue == null) {
                    break;
                }

                finalValue = (Map) ((Map) finalValue).get(separatorKeys[i]);
            }

        }
        return finalValue == null ? null : ((Map)finalValue).get(separatorKeys[separatorKeys.length - 1]);
    }

}
